package com.auto.netty.codec2;

import com.auto.netty.codec.StudentPOJO;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

//自定义处理器类，继承Netty的HandlerAdapter(处理器规范)
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * 读取数据事件，读取客户端发送的消息，
     *
     * @param ctx 上下文对象，包含管道pipeline和通道channel
     * @param msg 客户端发送的消息
     * @throws Exception
     */
    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
        MyDataInfo.MyMessage myMessage = (MyDataInfo.MyMessage) msg;
        MyDataInfo.MyMessage.DataType dataType = myMessage.getDataType();
        if (dataType == MyDataInfo.MyMessage.DataType.StudentType) {
            MyDataInfo.Student student = myMessage.getStudent();
            System.out.println("学生id = " + student.getId() + " 学生名字 = " + student.getName());
        } else if (dataType == MyDataInfo.MyMessage.DataType.WorkerType) {
            MyDataInfo.Worker worker = myMessage.getWorker();
            System.out.println("工人名字 = " + worker.getName() + " 工人年龄 = " + worker.getAge());
        } else {
            System.out.println("传输的类型不正确");
        }
    }

    /**
     * 数据读取完成后，给客户端响应数据，
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello，客户端-1", CharsetUtil.UTF_8));
    }

    /**
     * 处理异常，一般是关闭通道
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
